package com.atguigu.educenter.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.ConstantWxUtils;
import com.atguigu.educenter.utils.HttpClientUtils;
import com.atguigu.servicebase.exception.MyException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @Author: shaki
 * @Date: 2021/6/23 15:18
 */
@RequestMapping("/api/ucenter/wx")
@Slf4j
public class WxApiController {
    @Resource
    private UcenterMemberService memberService;
    //生成微信扫描二维码
    @GetMapping("/login")
    public String getWxCode(){
        // 微信开放平台授权baseUrl
        //? %s相当于占位符，可以填充参数
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //授权码需要传入加密过的URL,必须使用
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;//获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");//url编码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //设置%s参数值
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");
        //请求微信地址,重定向的方式
        return "redirect:" + url;
    }

    //扫码登录之后会跳转到callback方法中
    @GetMapping("/callback")
    public String callback(String code, String state){
        try{
            //1. 获取code，临时票据，类似验证码

            //2. 用code请求微信的固定地址，得到access_token和openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                    "appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //设置%s参数值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code);
            //使用HttpClient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            Gson gson = new Gson();
            HashMap accessTokenMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String)accessTokenMap.get("access_token");
            String openid = (String)accessTokenMap.get("openid");
            //将信息存入数据中，用openid判断
            UcenterMember member = memberService.getOpenIdMember(openid);
            if(member == null){
                //访问微信的资源服务器
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                        "access_token=%s" +
                        "&openid=%s";
                String UserInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid);
                String userInfo = HttpClientUtils.get(UserInfoUrl);
                //获取用户信息
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = userInfoMap.get("nickname").toString();
                String headimgurl = userInfoMap.get("headimgurl").toString().replace("\\","");
                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            //通过路径传递token，因为cookie不能跨域
            return "redirect:http://localhost:3000?token="+jwtToken;
        }catch (Exception e){
            throw new MyException(20001,"登录失败，用户已存在");
        }


    }
}
